package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.LoginRequest;
import com.pn.taikao.dto.LoginResponse;
import com.pn.taikao.dto.RegisterRequest;
import com.pn.taikao.dto.RegisterResponse;
import com.pn.taikao.entity.User;
import com.pn.taikao.service.CaptchaService;
import com.pn.taikao.service.UserService;
import com.pn.taikao.utils.JwtUtil;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final CaptchaService captchaService;

    public AuthController(UserService userService, JwtUtil jwtUtil, CaptchaService captchaService) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
        this.captchaService = captchaService;
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<RegisterResponse> register(@RequestBody RegisterRequest request) {
        // 验证验证码
        if (!captchaService.validateCaptcha(request.getCaptchaKey(), request.getCaptchaCode())) {
            return ApiResponse.error("验证码错误或已过期");
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setRealName(request.getRealName());
        user.setRoleType(request.getRoleType());
        user.setSex(request.getSex());
        user.setEmail(request.getEmail());
        user.setPhonenumber(request.getPhonenumber());
        
        Long id = userService.register(user);
        return ApiResponse.success(new RegisterResponse(id));
    }

    /**
     * 用户登录（支持用户名或邮箱 + 密码）
     */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@RequestBody LoginRequest request) {
        // 验证验证码
        if (!captchaService.validateCaptcha(request.getCaptchaKey(), request.getCaptchaCode())) {
            return ApiResponse.error("验证码错误或已过期");
        }
        
        User authed = userService.authenticate(request.getPrincipal(), request.getPassword());
        if (authed == null) {
            return ApiResponse.error("用户名或密码错误");
        }
        String token = jwtUtil.generateToken(authed.getId(), authed.getUsername(), authed.getRoleType());
        LoginResponse response = new LoginResponse(token, authed.getId(), authed.getUsername(), authed.getRoleType());
        return ApiResponse.success(response);
    }
}



